<template>
  <div style="display: flex; flex: 1;  ">
    <el-select popper-class="select_tree" ref="selectref" @visible-change="vc" @click.native="clickevent"
               v-model="value" placeholder="请选择" style="width: 100%;">
      <el-option :value="value" style="height: 240px; background: #fff">
        <el-tree style="height: 200px; overflow-y: auto;" v-loading="loading" highlight-current
                 :current-node-key="currentnodekey"
                 ref="tree" :data="data" node-key="id" default-expand-all @current-change="getCurrentKey"
                 :expand-on-click-node="false">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <input @blur="inputblur" ref="focus_input" v-model="data.label" v-if="data.id === currentnodekey && edit">
              <span style="user-select: none;" @dblclick="dbclick" v-else>
                <i style="margin-right: 2px;" class="el-icon-document"></i>{{ node.label }}
              </span>
            </span>
        </el-tree>
        <common-operation-form @click.stop.native
                               style="height: 40px; background: rgb(241,241,241); display: flex; align-items: center; justify-content: center; position: relative;"
                               :margin-right="'2px'" :list="buttonList"/>
      </el-option>
    </el-select>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import {getCustomerCategory, updateCustomerCategory} from "@/api/customerCategory";
import {getUserInfo} from "@/utils/auth";

function traverse(categories, findID) {
  for (let i = 0; i < categories.length; i++) {
    const category = categories[i];

    if (category.id === findID) {
      return category;
    }

    if (category.children && category.children.length > 0) {
      const result = traverse(category.children, findID);
      if (result) {
        return result;
      }
    }
  }

  return null;
}

function findParent(categories, findId, parent = null) {
  for (let i = 0; i < categories.length; i++) {
    const category = categories[i];

    if (category.id === findId) {
      return parent;
    }

    if (category.children && category.children.length > 0) {
      const result = findParent(category.children, findId, category);
      if (result) {
        return result;
      }
    }
  }

  return null;
}

function generateId() {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;

  for (let i = 0; i < 16; i++) {
    const randomIndex = Math.floor(Math.random() * charactersLength);
    result += characters.charAt(randomIndex);
  }

  return result;
}

export default {
  props: ["item"],
  components: {CommonOperationForm},
  data() {
    return {
      id: generateId(),
      value: '',
      edit: false,
      loading: false,
      data: [],
      currentnodekey: null,
      exitSelect: false,
      openSelect: false,
      buttonList: [
        {
          type: 'dropdown',
          contentname: "操作",
          command: (v) => {
            if(this.currentnodekey === null) {
              this.$message.error("请先选择一个分裂");
              return;
            }
            if (v === 0) {
              this.append();
            } else if (v === 1) {
              this.edit = true;
              this.$nextTick(() => {
                this.$refs.focus_input.focus()
              })
            } else {
              this.$confirm('您确认要删除当前分类吗?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning'
              }).then(() => {
                this.remove();
              }).catch(() => {

              });
            }
          },
          list: [{
            label: "创建分类",
            value: "",
            disable: false,
          }, {
            label: "重命名",
            value: "",
            disable: false,
          }, {
            label: "删除分类",
            value: "",
            disable: false,
          }],
        },
        {
          type: 'button',
          buttonText: '确认',
          size: 'mini',
          event: () => {
            this.dbclick();
          },
        },
        {
          type: 'button',
          buttonText: '退出',
          size: 'mini',
          event: () => {
            this.exitSelect = true;
            this.$refs['selectref'].visible = false;
          }
        }
      ],
    }
  },
  mounted() {
    this.getCustomerCategory();
    if (this.item)
      this.value = this.item.node;
  },
  methods: {
    getCustomerCategory() {
      if (this.loading)
        return;
      this.loading = true;
      getCustomerCategory({
        userID: getUserInfo().userID,
      }).then(res => {
        this.data = res.data.data.tree;
        this.loading = false;
        this.$nextTick(() => {
          this.getCurrentKey({id: this.item.value});
          this.getValueByID();
        });
      });
    },
    getValueByID() {
      let currentNode = traverse(this.data, this.item.value);
      if (currentNode)
        this.value = currentNode.label;
    },
    updateCustomerCategory(currentNode) {
      if (!currentNode) {
        currentNode = {
          id: this.currentnodekey,
        }
      }

      updateCustomerCategory({
        userID: getUserInfo().userID,
        treeData: this.data,
      }).then(res => {
        this.data = res.data.data.tree;
        this.$nextTick(() => {
          this.getCurrentKey({id: currentNode.id});
        });
      });
    },
    clickevent() {
      this.openSelect = !this.openSelect;
      if (this.openSelect === false) {
        this.exitSelect = true;
        this.$refs['selectref'].visible = false;
      }
    },
    dbclick() {
      let currentNode = traverse(this.data, this.currentnodekey);
      this.value = currentNode.label;
      this.exitSelect = true;
      this.$refs['selectref'].visible = false;

      this.$emit('selectTreeGetCurrentNode', this.item, this.getNodeInfo(currentNode));
    },
    getNodeInfo(v) {
      return {
        label: v.label,
        id: v.id,
      }
    },
    vc(v) {
      if (v === false && this.exitSelect === false) {
        this.$refs['selectref'].visible = true;
      }

      if (this.exitSelect) {
        this.exitSelect = false;
      }

    },
    inputblur() {
      this.updateCustomerCategory({
        id: this.currentnodekey,
      });
      this.edit = false;
    },
    getCurrentKey(v) {
      if (!this.$refs.tree)
        return;
      this.currentnodekey = v.id;
      this.$refs.tree.setCurrentKey(v.id);
      let list = this.buttonList[0].list;
      let disable = this.currentnodekey === 1;
      for (let i = 1; i < list.length; i++) {
        list[i].disable = disable;
      }
    },
    append() {
      this.id = this.id + 1;
      const newChild = {id: this.id, label: '新分类', children: []};
      let currentNode = traverse(this.data, this.currentnodekey);
      if (!currentNode.children) {
        this.$set(currentNode, 'children', []);
      }
      currentNode.children.push(newChild);
      this.updateCustomerCategory(currentNode);
    },
    remove() {
      const parent = findParent(this.data, this.currentnodekey);
      const children = parent.children || parent;
      const index = children.findIndex(d => d.id === this.currentnodekey);
      children.splice(index, 1);
      this.updateProductCategory(parent);
    }
  }
}
</script>


<style lang="scss">
.select_tree .el-select-dropdown__list {
  padding: 6px 0 0 0 !important;
}

.select_tree .el-select-dropdown__item {
  padding: 0 !important;
}

.box-card .el-card__body {
  padding: 10px;
}
</style>
